package cn.edu.xmu.server.service;

import cn.edu.xmu.server.util.MinioUtil;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Service
@RequiredArgsConstructor
public class UploadService {

    private final MinioUtil minioUtil;


    public Map<String, Object> initMultiPartUpload(String path, String filename, Integer partCount, String contentType) {
        path = path.replaceAll("/+", "/");
        if (path.indexOf("/") == 0) {
            path = path.substring(1);
        }
        String filePath = path + "/" + filename;

        Map<String, Object> result;
        if (partCount == 1) {
            String uploadObjectUrl = minioUtil.getUploadObjectUrl(filePath);
            result = ImmutableMap.of("uploadUrls", ImmutableList.of(uploadObjectUrl));
        } else {
            result = minioUtil.initMultiPartUpload(filePath, partCount, contentType);
        }

        return result;
    }


    public boolean mergeMultipartUpload(String objectName, String uploadId) {
        return minioUtil.mergeMultipartUpload(objectName, uploadId);
    }


//    public String uploadPart(MultipartFile file, String uploadId, Integer partNumber, String path, String filename) {
//        try {
//            String filePath = path + "/" + filename;
//            return minioUtil.uploadPart(file, uploadId, partNumber, filePath);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
}
